import $ from 'jquery'

var AppDB = {
    Server: "https://game.jixiucloud.cn/api/Games"
};

window.document.scripts.namedItem("jixiudb").src.split('?')[1].split('&').forEach(x => {
    var kv = x.split('=');
    AppDB[kv[0]] = kv[1];
});

/**
 * 查询数据
 * @param {any} _tableName 数据表名称
 * @param {any} _filter 查询条件
 * @param {any} _sort 排序
 * @param {any} _project 指定返回的字段
 * @param {any} _take 每页条数
 * @param {any} _skip 跳过多少条数据
 */
AppDB.Query = function (_tableName = AppDB.id, _filter = '', _sort ='', _project = '', _take = "10", _skip="0") {

    var queryParams = [
        `appID=${AppDB.id}`,
        `cName=${_tableName}`,
        `filter=${_filter}`,
        `sort=${_sort}`,
        `project=${_project}`,
        `take=${_take}`,
        `skip=${_skip}`,
        `api-version=2`
    ]

    return $.get(`${AppDB.Server}/Documents?${queryParams.join("&")}`);
}

/**
 * 添加数据
 * @param {any} _tableName 数据表名称
 * @param {any} _jsonStr json字符串
 */
AppDB.Post = function (_tableName = AppDB.id, _jsonStr = '') {

    var queryParams = [
        `appID=${AppDB.id}`,
        `cName=${_tableName}`,
        `api-version=2`
    ];

    var settings = {
        "url": `${AppDB.Server}/Document?${queryParams.join("&")}`,
        "method": "POST",
        "headers": {
            "Content-Type": "application/json"
        },
        data: _jsonStr,
    };

    return $.ajax(settings);
}

/**
 * 删除数据
 * @param {any} _tableName 数据表名称
 * @param {any} _filter 筛选条件
 */
AppDB.Delete = function (_tableName = AppDB.id, _filter = '') {

    var queryParams = [
        `appID=${AppDB.id}`,
        `cName=${_tableName}`,
        `filter=${_filter}`,
        `api-version=2`
    ];

    var settings = {
        "url": `${AppDB.Server}/Document?${queryParams.join("&")}`,
        "method": "DELETE"
    };

    return $.ajax(settings);
}

/**
 * 更新数据
 * @param {any} _tableName 数据表名称
 * @param {any} _filter 筛选条件
 * @param {any} _jsonStr json字符串
 */
AppDB.Put = function (_tableName = AppDB.id, _filter = '', _jsonStr = '') {

    var queryParams = [
        `appID=${AppDB.id}`,
        `cName=${_tableName}`,
        `filter=${_filter}`,
        `api-version=2`
    ];

    var settings = {
        "url": `${AppDB.Server}/Document?${queryParams.join("&")}`,
        "method": "PUT",
        "headers": {
            "Content-Type": "application/json"
        },
        "data": _jsonStr,
    };

    return $.ajax(settings);
}


/**
 * 数据表集合
 * */
AppDB.Tables = function () {
    var queryParams = [
        `appID=${AppDB.id}`,
        `api-version=2`
    ];

    return $.get(`${AppDB.Server}/Collections?${queryParams.join("&")}`);
}


export default AppDB